// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  let id = event.id
  const c = cloud.database().collection('questions')

  const totalRes = await c.where({
    qid: id
  }).count().then(res => {
    return res.total
  }).catch(err => {
    console.log(err)
    return 0
  })

  if (totalRes > 10) {
    return await c.aggregate().match({
      qid: id
    }).sample({
      size: 10
    }).end().then(res => {
      let l = []
      for (let i = 0; i < 10; i++) {
        let v = res.list[i]
        l.push({
          type: v.type,
          content: v.content,
          option_a: v['option_a'] || '',
          option_b: v['option_b'] || '',
          option_c: v['option_c'] || '',
          option_d: v['option_d'] || '',
          answer: v.answer,
          hint: v['hint'] || '',
          analysis: v['analysis'] || '',
          source: v['source'] || ''
        })
      }
      return l
    }).catch(err => {
      console.log(err)
    })
  } else if (totalRes > 0) {
    return await c.where({
      qid: id
    }).field({
      type: true,
      content: true,
      option_a: true,
      option_b: true,
      option_c: true,
      option_d: true,
      answer: true,
      hint: true,
      analysis: true,
      source: true
    }).get().then(res => {
      return res.data
    }).catch(err => {
      return err
    })
  } else {
    console.log('无数据')
  }
}